package com.wwg.springboard;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class FolderView extends FrameLayout {
    private List<Pair<Integer, String>> mData = new ArrayList<>();
    private MyAdapter myAdapter = new MyAdapter();

    public FolderView(@NonNull Context context) {
        this(context, null);
    }

    public FolderView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FolderView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public FolderView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        RecyclerView recyclerView = findViewById(R.id.rv_list);
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(myAdapter);
    }

    @SuppressLint("NotifyDataSetChanged")
    public void setData(List<Pair<Integer, String>> data) {
        mData = data;
        myAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }

    class MyAdapter extends RecyclerView.Adapter<MyHolder> {

        @NonNull
        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View inflate = inflater.inflate(R.layout.folder_item, parent, false);
            return new MyHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull MyHolder holder, int position) {
            if (mData == null) {
                return;
            }

            Pair<Integer, String> pair = mData.get(position);
            holder.imageView.setImageResource(pair.first);
        }

        @Override
        public int getItemCount() {
            if (mData == null) {
                return 0;
            }

            return mData.size();
        }
    }

    static class MyHolder extends RecyclerView.ViewHolder {
        final RadiusImageView imageView;

        public MyHolder(@NonNull View itemView) {
            super(itemView);
            imageView = (RadiusImageView) itemView;
        }
    }
}
